package com.ctgu.rabbitmq.rabbitmq.exchange.orderDemo;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.listener.api.RabbitListenerErrorHandler;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName DirectExchange
 * @Author Alex2
 * @Date 2025/3/12 17:29
 **/
@Log4j2
@Configuration
public class RabbitMQPaymentConfig {
    public static final String PAYMENT_EXCHANGE = "payment_exchange";
    public static final String PAYMENT_QUEUE = "payment_queue";

    // 创建直连交换机
    @Bean(PAYMENT_EXCHANGE)
    public DirectExchange exchange() {
        return new DirectExchange(PAYMENT_EXCHANGE, true, false);
    }

    // 创建队列
    @Bean(PAYMENT_QUEUE)
    public Queue payment_queue() {
        return QueueBuilder.durable(PAYMENT_QUEUE).build();
    }

    // 绑定队列和交换机（指定路由 key）
    @Bean
    public Binding bindingToInfo(@Qualifier(PAYMENT_EXCHANGE) DirectExchange exchange,
                                 @Qualifier(PAYMENT_QUEUE) Queue queue) {
        return BindingBuilder.bind(queue).to(exchange).with(PAYMENT_QUEUE);
    }

    // 自定义 RabbitMQ 消费异常处理器
    @Bean
    public RabbitListenerErrorHandler rabbitErrorHandler() {
        return (amqpMessage, message, exception) -> {
            log.error("RabbitMQ 消费异常：{}", exception.getMessage());
            throw exception; // 让消息重新入队
        };
    }

//    // JSON 消息转换器，将消息自动序列化/反序列化为对象
//    @Bean
//    public MessageConverter messageConverter() {
//        return new Jackson2JsonMessageConverter();
//    }
}